package main

import (
	"fmt"
	"time"
	"strconv"
	"crypto/md5"
	"net/http"
	"html/template"
)

func securePrint(w http.ResponseWriter, args ...interface{}) (int, error) {
	var str string = ""
	for _, v := range args {
		str = fmt.Sprint(str, v)
	}
	return fmt.Fprintln(w, template.HTMLEscaper(str))
}

func handleRoot(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	t, _ := template.ParseFiles("login.gtpl")
	t.Execute(w, nil)

	return
}

func handleLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method == http.MethodGet {
		unixtime := time.Now().Unix()
		hashToken := md5.New()
		fmt.Fprint(hashToken, strconv.FormatInt(unixtime, 10))
		token := fmt.Sprintf("%x", hashToken.Sum(nil))

		argsT := map[string]string {
			"unixtime": fmt.Sprint(unixtime),
			"token": token,
		}
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, argsT)
	} else if r.Method == http.MethodPost {
		if r.PostForm["username"][0] != "abc" ||
			r.PostForm["password"][0] != "123" {
			securePrint(w, "UserName or Password error.")
		} else {
			securePrint(w, "Get-Post UserName: ", r.Form.Get("username"))
			securePrint(w, "Get-Post2 UserName: ", r.Form["username"])
			securePrint(w, "UserName: ", r.PostForm["username"])
			securePrint(w, "PassWord: ", r.PostForm["password"])
			securePrint(w, "InputArea: ", r.PostForm["inputarea"])
			if r.PostForm.Get("remember") == "1" {
				securePrint(w, "Remember me.")
			} else {
				securePrint(w, "Do not remember me.")
			}
			securePrint(w, "CheckBox: ", r.PostForm["check"])
			securePrint(w, "UserType: ", r.PostForm["usertype"])
		}
	}

	return
}

